<?php
namespace app\middleware;

use common\behaviors\TrafficShaper;
use support\Container;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class RateLimitMiddleware implements MiddlewareInterface
{
    public function process(Request $request, callable $next) : Response
    {
        if (true === config('main.httpRateLimit')) {
            /** @var  $TrafficShaper TrafficShaper */
            $TrafficShaper = Container::get(TrafficShaper::class);
            if (!$TrafficShaper->rateLimit($request->getLocalIp(), $request->uri())) {
                return app('json')->fail('服务器繁忙、访问太火爆、请稍候.....');
            }
        }
        return $next($request);
    }
    
}
